import fg from 'fast-glob'
import { normalizePath } from 'vite'

// 静态图片资源 预加载 vite 插件
export const vitePluginImagePreload = (config = {}) => {
  const defaultConfig = {
    cwd: 'src/assets/images/',
    match: '*.{jpg,png}',
    injectTo: 'head',
  }
  const mergedConfig = { ...defaultConfig, ...config }
  const { cwd, match, injectTo } = mergedConfig
  return {
    name: 'vite-plugin-image-preload',
    transformIndexHtml(_html, ctx) {
      const { base } = ctx.server.config
      const files = fg.sync(match, { cwd })
      const links = files.map(fileName => {
        return {
          tag: 'link',
          injectTo,
          attrs: {
            rel: 'preload', // prefetch
            as: 'image',
            href: normalizePath(base + cwd + fileName)
          }
        }
      })
      return links
    }
  }
}
